package com.lenovo.nova.widget.baseview;

import android.content.Context;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.EditText;
import android.widget.GridLayout;
import com.lenovo.nova.util.StringUtil;

/**
 * Created by scenic on 2015/3/29.
 */
public class GridEditView extends GridLayout{

    private EditText mEdiTexts[] ;
    private int columnCount;
    private int rowCount;

    public GridEditView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLayout();
    }
    
    private void initLayout(){
        post(new Runnable() {
            @Override
            public void run() {
                columnCount = getColumnCount();
                rowCount = getRowCount();

                int width = getWidth() / columnCount;
                int height = getHeight() / rowCount;
                addEdiText(width,height);

                resetEditTextValue();
            }
        });
    }


    public float[] getValues(){
        int allCount = columnCount*rowCount;
        float[] values =new float[allCount];
        for(int i=0; i < allCount;i++){
            if(!StringUtil.isStringEmpty(mEdiTexts[i].getText())){
                values[i]= Float.parseFloat(mEdiTexts[i].getText().toString());
            }
        }
        return values;
    }

    public void resetEditTextValue(){
        int allCount = columnCount*rowCount;

        for (int i =0 ;i < allCount ;i ++){
            if(i % (columnCount + 1) == 0){
                mEdiTexts[i].setText(""+1);
            }else {
                mEdiTexts[i].setText("0");
            }
        }
    }

    private void addEdiText(int textWidth, int textHeight) {
        int allCount = columnCount*rowCount;
        mEdiTexts = new EditText[allCount];
        for(int i = 0;i < mEdiTexts.length; i++){
            EditText ediText = new EditText(getContext());
            ediText.setGravity(Gravity.CENTER);
            ediText.setInputType(InputType.TYPE_CLASS_NUMBER);
            mEdiTexts[i] = ediText;

            addView(ediText, textWidth, textHeight);
        }
    }

}
